<?php


namespace App\Api\Controllers;

use App\Models\Course;
use App\Models\CourseList;
use App\Models\LearnCourse;
use Illuminate\Http\Request;

class CourseController extends Controller
{
    //一级课程
    public function course(Request $request)
    {
        $data = Course::all()->toArray();
        return $this->responseData($data);
    }

    //二级课程
    public function courseList(Request $request)
    {
        if(!$request->course_id){
            return $this->responseFailed('course_id必传');
        }
        $list = CourseList::where('course_id', $request->course_id)
            ->get()
            ->toArray();
        return $this->responseData($list);
    }

    public function addLearn(Request $request)
    {
        try{
            $user = auth()->user();
            if(!$request->id_list){
                return $this->responseFailed('参数必传');
            }
            $id_list = $request->id_list;
            if(is_string($id_list))
            {
                $id_list = json_decode($id_list,true);
            }
            if (!is_array($id_list)) {
                return $this->responseFailed('id_list格式错误');
            }
            foreach($id_list as $val){
                $where = [
                    ['course_list_id', '=', $val],
                    ['user_id', '=', $user['id']],
                    ['deal_time', '=', date('Y-m-d')],
                ];
                $model = LearnCourse::where($where)->first();
                if (!$model) {
                    $model = new LearnCourse();
                }
                $course = CourseList::find($val);
                if(!$course){
                    uexception('课程不存在');
                }
                $model->region_id = $user['region_id'];
                $model->store_id = $user['store_id'];
                $model->course_id = $course['course_id'];
                $model->course_list_id = $val;
                $model->user_id = $user['id'];
                $model->num = $request->num;
                $model->deal_time = date('Y-m-d');
                $model->save();
            }
            return $this->responseSuccess();
        }catch (\Exception $e){
            return $this->responseFailed($e->getMessage());
        }
    }

    public function rate(Request $request)
    {
        $date = $request->deal_time?:date('Y-m-d');
        $input = $request->only([
            'store_id',
            'region_id',
        ]);
        $data = Course::getRate($input, $date);
        return $this->responseData($data);
    }

}